<?php
/**
 * @author Adam Zivner <adam.zivner@gmail.com>
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD license
 * @package AttoMVC https://code.google.com/p/attomvc/
 */

class AttoHelperURL {
	private static $instance;
	public $file_path = "index.php";

	/** @return AttoHelperURL */
	public static function getInstance()
	{
		if(self::$instance == false)
			self::$instance = new self;

		return self::$instance;
	}

	/**
	 * This object is used as a singleton. Singleton is hard to extend or mock.
	 * This makes it possible to replace the object with something different ...
	 */

	public static function setInstance($instance)
	{
		self::$instance = $instance;
	}

	/**
	 * Return a relative URL from given parameter pairs.
	 *
	 * @param array $params
	 * @return string
	 */

	public function url($params)
	{
		return $this->file_path . "?" . http_build_query($params, "", "&");
	}

	/**
	 * Redirect to the specified URL. This method does not return (dies).
	 *
	 * @param string|array $params
	 */

	public function redirect($params)
	{
		if(is_string($params))
			$url = $params;
		else
			$url = $this->url($params);

		header("Location: $url");
		die();
	}

	/**
	 * Solves the problem with two parameter separators in URL - ? and &
	 * Problem is when you want to add a parameter to the URL and you don't
	 * know whether you should use ? or &.
	 *
	 * @param string $url
	 * @param array $params
	 * @return string
	 */

	public function addParamsToURL($url, $params)
	{
		if(count($params))
			$url .= strpos($url, "?") === false ? "?" : "&";

		$pairs = array();

		foreach($params as $name => $value)
			$pairs[] = urlencode($name) . "=" . urlencode($value);

		return $url . implode("&", $pairs);
	}
}